import Checkbox from "../../inner/Checkbox";
import { PropType, computed, defineComponent, ref, watchEffect } from "vue";
import formFieldRef from "../../use/formFieldRef";

type CheckboxGroupProps = {
    block?: boolean,
    name?: string,
    value?: any[],
    modelValue?: any[],
    disabled?: boolean,
    data?: any,
    textField?: string,
    valueField?: string,
    asFormField?: boolean,
}

export default defineComponent({
    name: "CheckboxGroup",
    props: {
        block: {
            type: Boolean as PropType<CheckboxGroupProps['block']>,
        },
        name: {
            type: String as PropType<CheckboxGroupProps['name']>,
        },
        value: {
            type: Array as PropType<CheckboxGroupProps['value']>,
        },
        modelValue: {
            type: Array as PropType<CheckboxGroupProps['modelValue']>,
        },
        disabled: {
            type: Boolean as PropType<CheckboxGroupProps['disabled']>,
        },
        data: {
            type: Array as PropType<CheckboxGroupProps['data']>,
        },
        textField: {
            type: String as PropType<CheckboxGroupProps['textField']>,
        },
        valueField: {
            type: String as PropType<CheckboxGroupProps['valueField']>,
        },
        asFormField: {
            type: Boolean as PropType<CheckboxGroupProps['asFormField']>, default: true
        },
    },
    emits: ['change', 'update:modelValue'],
    setup (props: CheckboxGroupProps, { emit }){
        const classList = computed(() => ({
            'cm-checkbox-group': true,
            'cm-checkbox-group-stack': props.block
        }));
        const value = formFieldRef(props, emit, []);

        const _onChange = (checked: boolean, v: any) => {
            if (props.disabled) {
                return;
            }
            let val: any[] = value.value || [];
            if (checked) {
                if (!val.includes(v)) {
                    val = val.concat(v);
                }
            } else {
                const index = val.indexOf(v);
                if (index > -1) {
                    val.splice(index, 1);
                }
            }
            const newVal = JSON.parse(JSON.stringify(val));
            value.value = newVal;
            emit('change', newVal);
        };
        const textField = props.textField || 'label';
        const valueField = props.valueField || 'value';

        // 子元素的控制
        const controllers: any = {};
        if (props.data) {
            props.data.forEach((item: any) => {
                const val: any[] = value.value || [];
                const checked = val.includes(item[valueField]);
                controllers[item[valueField]] = ref(checked);
            });
        }

        watchEffect(() => {
            const val: any[] = value.value ?? [];
            for (let i = 0; i < props.data.length; i++) {
                const item = props.data[i];
                const checked = val.includes(item[valueField]);
                controllers[item[valueField]].value = checked;
            }
        });

        return () => <div class={classList.value}>
            {
                props.data.map((item: any) => {
                    return <Checkbox disabled={props.disabled || item.disabled} value={item[valueField]} checked={controllers[item[valueField]].value} label={item[textField]} onChange={_onChange}></Checkbox>;
                })
            }
        </div>;
    },
});
